/*
 *    Copyright 2022 The DSMS Authors.
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *        http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */

package com.dsms.modules.util;

import cn.hutool.core.util.StrUtil;
import com.dsms.common.constant.SystemConst;
import com.dsms.common.prometheus.builder.QueryBuilder;
import com.dsms.common.prometheus.builder.QueryBuilderType;
import com.dsms.dfsbroker.cluster.model.Cluster;
import com.dsms.dfsbroker.cluster.service.IClusterService;
import org.apache.http.client.HttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.security.web.util.UrlUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import javax.annotation.PostConstruct;

@Component
public class PrometheusUtil {

    private static String prometheusPort;
    private static PrometheusUtil prometheusUtil;
    @Value("${prometheus.port}")
    private String port;
    @Autowired
    private IClusterService clusterService;

    private static RestTemplate prometheusTemplate;

    public PrometheusUtil(){
        HttpComponentsClientHttpRequestFactory httpRequestFactory = new HttpComponentsClientHttpRequestFactory();
        httpRequestFactory.setConnectTimeout(1000);
        httpRequestFactory.setReadTimeout(2000);
        HttpClient httpClient = HttpClientBuilder.create()
            .setMaxConnTotal(100)
            .setMaxConnPerRoute(10)
            .build();
        httpRequestFactory.setHttpClient(httpClient);
        prometheusTemplate = new RestTemplate(httpRequestFactory);
    }

    public static <T extends QueryBuilder> T getQueryBuilder(QueryBuilderType queryBuilderType) {
        Cluster currentBindCluster = prometheusUtil.clusterService.getCurrentBindCluster();
        String url = UrlUtils.buildFullRequestUrl(SystemConst.HTTP_SCHEME, currentBindCluster.getClusterAddress(), Integer.parseInt(prometheusPort), StrUtil.EMPTY, null);
        return queryBuilderType.newInstance(url);
    }

    public static RestTemplate generatePrometheusTemplate() {
        return prometheusTemplate;
    }

    @PostConstruct
    public void init() {
        prometheusPort = this.port;
        prometheusUtil = this;
        prometheusUtil.clusterService = this.clusterService;
    }
}
